package com.yanqu.road.server.manager.activity.zhenhuan;

import com.yanqu.road.dao.impl.activity.zhenhuan.CrossZhenHuanPromotionImpl;
import com.yanqu.road.entity.activity.ActivityInfo;
import com.yanqu.road.entity.activity.zhenhuan.CrossZhenHuanPromotionData;
import com.yanqu.road.entity.activity.zhenhuan.ZhenHuanPromotionInfo;
import com.yanqu.road.entity.enums.activity.zhenhuan.eZhenHuanChildType;
import com.yanqu.road.entity.enums.eGamePlayerEventType;
import com.yanqu.road.entity.rank.cross.CrossUserRank;
import com.yanqu.road.logic.activity.zhenhuan.ZhenHuanPb;
import com.yanqu.road.logic.cross.CrossActivityRankListModel;
import com.yanqu.road.pb.activity.ZhenHuanProto;
import com.yanqu.road.server.logic.MessageHelper;
import com.yanqu.road.server.manager.activity.ActivityRankMgr;
import com.yanqu.road.server.protocol.GameProtocol;
import com.yanqu.road.sync.message.SyncResponse;
import com.yanqu.road.utils.date.DateHelper;

import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;

public class CrossZhenHuanPromotionActivity {
    private int activityId;
    private int childType;
    /**
     * key:serverId
     */
    private Map<Long, CrossZhenHuanPromotionData> promotionDataMap = new ConcurrentHashMap<>();
    /**
     * 晋级时间秒 活动结束后2分钟
     */
    private long promotionTime;
    private int conditionType = 0;
    private boolean isAllSync = false;

    public CrossZhenHuanPromotionActivity(ActivityInfo activityInfo) {
        this.activityId = activityInfo.getActivityId();
        this.childType = activityInfo.getChildType();
        this.promotionTime = activityInfo.getEndTime() + 120;
        if (activityInfo.getChildType() == eZhenHuanChildType.First.getValue()) {
            this.conditionType = eGamePlayerEventType.ZhenHuanFirstProcessRank.getValue();
        } else if (activityInfo.getChildType() == eZhenHuanChildType.Second.getValue()) {
            this.conditionType = eGamePlayerEventType.ZhenHuanSecondProcessRank.getValue();
        }

        loadDbData();
    }

    public void loadDbData() {
        promotionDataMap = new CrossZhenHuanPromotionImpl().getCrossZhenHuanPromotionDataMap(activityId);
    }

    public int getActivityId() {
        return activityId;
    }

    public int getChildType() {
        return childType;
    }

    public long getPromotionTime() {
        return promotionTime;
    }

    public int getConditionType() {
        return conditionType;
    }

    public boolean isAllSync() {
        return isAllSync;
    }

    public Map<Long, CrossZhenHuanPromotionData> getPromotionDataMap() {
        return promotionDataMap;
    }

    /**
     * 晋升任务,获得晋升名单
     */
    public void promotionTask() {
        int currentSecond = DateHelper.getCurrentSecond();
        if (currentSecond < this.promotionTime) {
            return;
        }

        if (!promotionDataMap.isEmpty()) {
            return;
        }

        if (conditionType == 0) {
            return;
        }

        int promotionNum = CrossZhenHuanConfigMgr.getPromotionNum(activityId);
        if (promotionNum <= 0) {
            return;
        }

        CrossActivityRankListModel rankListModel = ActivityRankMgr.getCrossActivityNewRankListModel(activityId, conditionType);
        if (rankListModel == null) {
            return;
        }

        Map<Long, List<ZhenHuanPromotionInfo>> promotionListMap = new HashMap<>();

        LinkedList<CrossUserRank> rankList = rankListModel.getRankList();
        for (int i = 0; i < rankList.size() && i < promotionNum; i++) {
            int rank = i + 1;
            CrossUserRank crossUserRank = rankList.get(i);
            long serverId = crossUserRank.getUserBaseInfo().getServerId();

            ZhenHuanPromotionInfo promotionInfo = new ZhenHuanPromotionInfo();
            promotionInfo.setUserId(crossUserRank.getUserId());
            promotionInfo.setRank(rank);
            promotionInfo.setValue(crossUserRank.getValue());
            promotionInfo.setLastUpdateTime(crossUserRank.getLastUpdateTime());
            promotionInfo.setParam(crossUserRank.getParam());

            List<ZhenHuanPromotionInfo> list = promotionListMap.get(serverId);
            if (list == null) {
                list = new ArrayList<>();
                promotionListMap.put(serverId, list);
            }
            list.add(promotionInfo);
        }

        for (Map.Entry<Long, List<ZhenHuanPromotionInfo>> entry : promotionListMap.entrySet()) {
            long serverId = entry.getKey();
            CrossZhenHuanPromotionData promotionData = new CrossZhenHuanPromotionData(activityId, childType, serverId);
            promotionData.setPromotionInfoList(entry.getValue());

            synchronized (promotionDataMap) {
                promotionDataMap.put(promotionData.getServerId(), promotionData);
            }
        }

        isAllSync = false;
    }

    /**
     * 同步晋升名单到各个游戏服
     */
    public void syncPromotionTask() {
        if (promotionDataMap.isEmpty()) {
            return;
        }
        if (isAllSync) {
            return;
        }
        boolean check = true;
        for (CrossZhenHuanPromotionData promotionData : promotionDataMap.values()) {
            if (promotionData.getGameServerConfirm() != 0) {
                continue;
            }
            check = false;
            long serverId = promotionData.getServerId();
            List<ZhenHuanProto.ZhenHuanPromotionTemp> promotionTemps = ZhenHuanPb.parsePromotionTempList(promotionData.getPromotionInfoList());
            ZhenHuanProto.ZhenHuanPromotionListSyncMsg.Builder syncMsg = ZhenHuanProto.ZhenHuanPromotionListSyncMsg.newBuilder();
            syncMsg.setActivityId(activityId);
            syncMsg.addAllInfo(promotionTemps);

            ZhenHuanProto.ZhenHuanPromotionListSyncConfirmMsg.Builder confirmMsg = ZhenHuanProto.ZhenHuanPromotionListSyncConfirmMsg.newBuilder();

            CompletableFuture<SyncResponse> future = MessageHelper.sendToGameServer(serverId, GameProtocol.S_ZHENHUAN_PROMOTION_SYNC_CROSS_BACK, activityId, 0, syncMsg, confirmMsg);
            future.thenAccept(response -> {
                if (response.getErrorCode() != 0) {
                    CrossZhenHuanMgr.getLogger().error("syncPromotionTask error, serverId:{}, errorCode:{}", serverId, response.getErrorCode());
                    return;
                }

                promotionData.setGameServerConfirm(1);
            });
        }

        isAllSync = check;
    }

    public void save() {
        List<CrossZhenHuanPromotionData> saveDataList = new ArrayList<>();
        synchronized (promotionDataMap) {
            saveDataList.addAll(promotionDataMap.values());
        }

        for (CrossZhenHuanPromotionData promotionData : saveDataList) {
            if (promotionData.isInsertOption()) {
                new CrossZhenHuanPromotionImpl().add(promotionData);
            } else if (promotionData.isUpdateOption()) {
                new CrossZhenHuanPromotionImpl().update(promotionData);
            }
        }

    }

}
